import type { DATA, DBFUN } from '../db'
import * as localforage from "localforage";
import { saveAs } from 'file-saver'
import dayjs from 'dayjs'

export class IndexDB implements DBFUN {
    db: any
    key: string
    DBName: string
    constructor(dbKey: string, dbName: string) {
        this.key = dbKey
        this.DBName = dbName
        this.db = localforage.createInstance({
            name: this.DBName,
            storeName: 'v__mock',
        })
    }
    setDB(data: DATA | DATA[]) {
        new Promise((resolve, reject) => {
            this.db.getItem(this.key).then(value => {
                resolve(value || [])
            }).catch(() => {
                resolve([])
            })
        }).then((dataList: any) => {
            if (Array.isArray(data)) {
                for (const d of data) {
                    const index = dataList.findIndex(a => d.url === a.url && d.method === a.method && d.body === a.body)
                    if (index !== -1) {
                        dataList[index] = d
                    } else {
                        dataList = [ ...dataList, d ]
                    }
                }
                this.db.setItem(this.key, dataList)
            } else {
                const index = dataList.findIndex(d => d.url === data.url && d.method === data.method && d.body === data.body)
                if (index !== -1) {
                    dataList[index] = data
                } else {
                    dataList = [ ...dataList, data ]
                }
                this.db.setItem(this.key, dataList)
            }
        })
    }
    getDB(): Promise<DATA[]> {
        return new Promise((resolve, reject) => {
            this.db.getItem(this.key).then((value) => {
                resolve(value || [])
            }).catch(() => {
                resolve([])
            })
        })
    }
    clear() {
        this.db.removeItem(this.key)
    }
    async downloadDBJson(fn?: Function) {
        const list = await this.getDB()
        if (list.length > 0) {
            const l = fn ? fn(list) : list;
            const file = new File([JSON.stringify(l)], `mock.${dayjs().format('YYYY-MM-DD HH:mm:ss')}.json`, {type: "text/plain;charset=utf-8"})
            saveAs(file)
        } else {
            console.error('未捕捉到任何接口数据')
        }
    }
}

export default IndexDB